import axios from "axios"
import router from '@/router'
import { showToast } from "@nutui/nutui";
import userUtils from "@/utils/userUtils"

const instance = axios.create({
    baseURL: window["baseURL"],
    widthCredentials: true,
    timeout: 5000
})

//发送数据之前
instance.interceptors.request.use(
    //拦截成功执行的函数
    //config包含网络请求的所有信息
    config => {
        // 设置登录token
        config.headers["x-auth-token"] = userUtils.getToken();
        if(config.data && config.data.repeatSubmitToken) {
            config.headers["repeat-submit-token"] = config.data.repeatSubmitToken;
        }
        
        return config
    },
    //拦截失败执行的函数
    error => {
        return Promise.reject(error)
    }
)

//获取数据之前
instance.interceptors.response.use(
    //成功时返回结果
    response => {
        if (null == response || null == response.data || response.status != 200) {
            showToast.fail(response.data.msg)
            return Promise.reject(response)
        }

        //登录失效
        if (response.data.code == 9999) {
            router.push({ path: '/login' })
            return Promise.reject(response)
        }

        //访问成功
        if (response.data.code == 200) {
            // 设置登录token
            if (response.headers && response.headers["x-auth-token"]) {
                userUtils.setToken(response.headers["x-auth-token"]);
            }
            return Promise.resolve(response.data);
        }

        //访问失败
        showToast.fail(response.data.msg)
        return Promise.reject(response);

    },
    //失败时返回结果
    error => {
        return Promise.reject(error)
    }
)
export default instance